package com.noah.project.global

import java.util.*
import java.util.concurrent.ConcurrentHashMap

/**
 * Created by zzh on 2018/7/11.
 */

object TokenManager {
    val tokenMap = ConcurrentHashMap<Long, String>()
    val decoder = Base64.getDecoder()
    val encoder = Base64.getEncoder()

    fun checkToken(token: String?): Boolean {
        if (token != null) {
            if (tokenMap.containsValue(token)) {
                val tokenStr = String(decoder.decode(token.toByteArray()))
                if (tokenStr.contains(":")) {//必须有":"
                    val time = tokenStr.split(":")[1]
                    if (System.currentTimeMillis() - time.toLong() < 604800000) {//必须小于7天
                        return true
                    }
                }
            } else if (token == Const.TEST_TOKEN) {
                return true
            }
        }
        return false
    }

    fun updateToken(uid: Long?): String? {
        if (uid == null) {
            return null
        }
        if (tokenMap.containsKey(uid)) {
            tokenMap.remove(uid)
        }
        val text = uid.toString() + ":" + System.currentTimeMillis()
        val token = encoder.encodeToString(text.toByteArray())
        tokenMap.put(uid, token)
        return token
    }
}
